package com.yunxun.coinmessage.service;
import com.yunxun.coinmessage.dao.PushListDao;
import com.yunxun.coinmessage.entity.Content;

import com.yunxun.coinmessage.entity.PushList;
import com.yunxun.coinmessage.entity.User;
import com.yunxun.coinmessage.templatedata.MsgResult;
import com.yunxun.coinmessage.templatedata.PushListTemplateData;
import com.yunxun.coinmessage.sqlvo.PushListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class PushListService {
    @Autowired
    PushListDao pushListDao;
    @Autowired
    SubscribeService subscribeService;
    @Autowired
    ProgramService programService;
    @Autowired
    UserService userService;
    @Autowired
    ContentService contentService;
    /**
     * 新增推送列表
     *
     * @param content
     */
    public void addPushList(Content content) {
        List<Integer> uidList = new ArrayList<Integer>();
        int userTotal = 0;//记录订阅了该资讯的总用户数量
        int start = 0; //记录查询开始位置
        if (content.getProgram_id() == 1) {
            //不为空即是政策类的快讯，推送给订阅了快讯的所有用户
            if ("精选".equals(content.getSort())) {
                userTotal = subscribeService.queryQuickNewsTotal();
                while (start < userTotal) {
                    uidList.clear();
                    uidList = subscribeService.queryQuickNewsUser(start,100);
                    //遍历查询出的100个用户；
                    for (int uid : uidList) {
                        User user = userService.queryById(uid);
                        pushListDao.addPushItem(getPushListVO(
                                content.getCon_id(),
                                content.getCon_title(),
                                content.getProgram_id(),
                                user.getUid(),
                                programService.queryNameById(content.getProgram_id()),//根据资讯的栏目id查询出栏目名称
                                user.getUname()));//向推送列表中新增一条推送条目
                    }
                    start += 99;//每次while循环让起始点加99（因为起始点是从0开始计算的）
                }
                return;//让方法结束
            }
        }
        // 不是精选快讯
        queryAllUserAndAddPushList(content);
    }

    /**
     * 组装pushListDao中的addPushList方法的参数
     *
     * @param con_id
     * @param con_title
     * @param program_id
     * @param uid
     * @param program_name
     * @param uname
     */
    public PushListVO getPushListVO(int con_id, String con_title, int program_id, int uid, String program_name, String uname) {
        PushListVO pushListVO=new PushListVO();
        pushListVO.setProgram_id(program_id);
        pushListVO.setCon_id(con_id);
        pushListVO.setCon_title(con_title);
        pushListVO.setUid(uid);
        pushListVO.setRank(System.currentTimeMillis() / 1000);
        pushListVO.setCome_timestamp(System.currentTimeMillis() / 1000);
        pushListVO.setProgram_name(program_name);
        pushListVO.setUname(uname);
        return pushListVO;
    }

    /**
     * 通过给定的资讯在订阅列表查找订阅用户总数并循环取出
     *
     * @param content//新增资讯
     */
    public void queryAllUserAndAddPushList(Content content) {
        List<Integer> uidList = new ArrayList<Integer>();
        int userTotal = 0;//记录订阅了该资讯的总用户数量
        int start = 0; //记录查询开始位置
        if(content.getProgram_id() == 2 || content.getProgram_id() == 1){
            if( content.getCoin_id()==0){//不属于任何模型的普通市场快讯，或不属于任何模型的币种跟踪，不推送给任何用户
                return;
            }
            //找到订阅了该币种的总用户数
            userTotal = subscribeService.queryCountByContent(2,content.getCoin_id());
            //如果是关于某个币种的快讯，需要将未订阅快讯的用户排除
            if(content.getProgram_id()==1){
                start=0;
                while (start < userTotal) {
                    uidList.clear();
                    uidList = subscribeService.queryUidByContent(2, content.getCoin_id(), start, 100);
                    Iterator it=uidList.iterator();
                    while (it.hasNext()){
                        int uid=(int)it.next();
                        if(subscribeService.judgeSubQuikNews(uid)==0){
                            it.remove();
                        }
                    }
                    //遍历查询出订阅了快讯的                                                                                                                                                                                              用户；
                    for (int uid : uidList) {
                        User user = userService.queryById(uid);
                        pushListDao.addPushItem(   getPushListVO(
                                content.getCon_id(),
                                content.getCon_title(),
                                content.getProgram_id(),
                                user.getUid(),
                                programService.queryNameById(content.getProgram_id()),//根据资讯的栏目id查询出栏目名称
                                user.getUname()));//向推送列表中新增一条推送条目
                    }
                    start += 99;//每次while循环让起始点加99（因为起始点是从0开始计算的）
                }
            }else{//表示币种跟踪
                while (start < userTotal) {
                    start=0;
                    uidList.clear();
                    uidList = subscribeService.queryUidByContent(2, content.getCoin_id(), start, 100);
                    //遍历查询出的100个用户；
                    for (int uid : uidList) {
                        User user = userService.queryById(uid);
                        pushListDao.addPushItem(   getPushListVO(
                                content.getCon_id(),
                                content.getCon_title(),
                                content.getProgram_id(),
                                user.getUid(),
                                programService.queryNameById(content.getProgram_id()),//根据资讯的栏目id查询出栏目名称
                                user.getUname()));//向推送列表中新增一条推送条目
                    }
                    start += 99;//每次while循环让起始点加99（因为起始点是从0开始计算的）
                }
            }
        }else {//交易所公告
            //属于交易所的公告
            if(content.getExchange_id()!=0){
                start=0;
                userTotal = subscribeService.queryCountByContent(content.getProgram_id(), content.getExchange_id());
                while (start < userTotal) {
                    uidList.clear();
                    uidList = subscribeService.queryUidByContent(content.getProgram_id(), content.getExchange_id(), start, 100);
                    //遍历查询出的100个用户；
                    for (int uid : uidList) {
                        User user = userService.queryById(uid);
                        pushListDao.addPushItem(getPushListVO(
                                content.getCon_id(),
                                content.getCon_title(),
                                content.getProgram_id(),
                                user.getUid(),
                                programService.queryNameById(content.getProgram_id()),//根据资讯的栏目id查询出栏目名称
                                user.getUname()));//向推送列表中新增一条推送条目
                    }
                    start += 99;//每次while循环让起始点加99（因为起始点是从0开始计算的）
                }
            }
            //属于币种的交易所公告
            if(content.getCoin_id()!=0){
                start=0;
                userTotal=subscribeService.queryExchangeTotal();
                while (start<userTotal){
                    uidList.clear();
                    uidList=subscribeService.queryExchangeUid(start,100);
                    Iterator it=uidList.iterator();
                    while (it.hasNext()){
                        int uid=(int)it.next();
                        //只要有一个条件成立即移除它
                        if(subscribeService.judgeSubCoin(uid,content.getCoin_id()) == 0 || subscribeService.judgeSubExchange(uid) == 0){
                            it.remove();
                        }
                    }
                    for(int uid:uidList){
                        User user=userService.queryById(uid);
                        //进推送列表前判断是否已在推送列表中
                        if(pushListDao.judgeUidComePushList(content.getCon_id(),uid)!=0){
                            //存在即结束本次循环
                            continue;
                        }
                        pushListDao.addPushItem(getPushListVO(
                                content.getCon_id(),
                                content.getCon_title(),
                                content.getProgram_id(),
                                user.getUid(),
                                programService.queryNameById(content.getProgram_id()),//根据资讯的栏目id查询出栏目名称
                                user.getUname()));//向推送列表中新增一条推送条目
                    }
                    start+=99;
                }
            }
        }
    }


    public List<PushListTemplateData> queryPushListModels(int start, int limit) {
        List<PushListTemplateData> pushListTemplateDataList = new ArrayList<>();

        List<PushList> pushLists = pushListDao.queryAllPushList(start, limit);
        for (PushList pushList : pushLists) {
            PushListTemplateData pushListTemplateData = new PushListTemplateData();
            pushListTemplateData.setProgram_name(pushList.getProgram_name());
            pushListTemplateData.setCon_title(pushList.getCon_title());
            pushListTemplateData.setCon_id(pushList.getCon_id());
            //判断推送状态
            if (pushListDao.querySuccessTotal(pushList.getCon_id()) == 0) {
                pushListTemplateData.setStatus(0);//状态为0表示未推送
            } else if (pushListDao.querySuccessTotal(pushList.getCon_id()) == pushListDao.queryTotalByConId(pushList.getCon_id())) {
                pushListTemplateData.setStatus(1);//状态为1表示推送成功
            } else if (pushListDao.querySuccessTotal(pushList.getCon_id()) + pushListDao.queryfailureTotal(pushList.getCon_id()) == pushListDao.queryTotalByConId(pushList.getCon_id())) {
                pushListTemplateData.setStatus(2);//状态为2表示部分推送失败
                pushListTemplateData.setSuccessCount(pushListDao.querySuccessTotal(pushList.getCon_id()));//查询推送成功的总条数
                pushListTemplateData.setFailureCount(pushListDao.queryfailureTotal(pushList.getCon_id()));//查询推送失败的总条数
            } else {
                pushListTemplateData.setStatus(3);//正在推送
            }
            pushListTemplateDataList.add(pushListTemplateData);
        }
        return pushListTemplateDataList;
    }

    public int queryContentTotal() {
        return pushListDao.queryContentTotal();
    }

    /**
     * 查询推送成功的用户
     *
     * @param con_id
     * @param start
     * @param limit
     * @return
     */
    public List<PushList> querySuccessUser(int con_id, int start, int limit) {
        List<PushList> pushLists = pushListDao.querySuccessUser(con_id, start, limit);
        for (PushList pushList : pushLists) {
            pushList.setFormatTime(pushList.getLast_timestamp());
        }
        return pushLists;
    }

    /**
     * 查询推送失败的用户
     *
     * @param con_id
     * @param start
     * @param limit
     * @return
     */
    public List<PushList> queryFailureUser(int con_id, int start, int limit) {
        List<PushList> pushLists = pushListDao.queryfailureUser(con_id, start, limit);
        for (PushList pushList : pushLists) {
            pushList.setFormatTime(pushList.getLast_timestamp());
        }
        return pushLists;
    }

    /**
     * 查询谋篇资讯要推送的所有用户
     *
     * @param con_id
     * @param start
     * @param limit
     * @return
     */
    public List<PushList> queryAllUserByConId(int con_id, int start, int limit) {
        List<PushList> pushLists = pushListDao.queryAllUserByConId(con_id, start, limit);
        for (PushList pushList : pushLists) {
            pushList.setFormatTime(pushList.getLast_timestamp());
        }
        return pushLists;
    }

    /**
     * 查询某条资讯要推送的总用户数量
     *
     * @param con_id
     * @return
     */
    public int queryTotalByConId(int con_id) {
        return pushListDao.queryTotalByConId(con_id);
    }

    public int querySuccessTotal(int con_id) {
        return pushListDao.querySuccessTotal(con_id);
    }

    public int queryFailureTotal(int con_id) {
        return pushListDao.queryfailureTotal(con_id);
    }

    /**
     * 一键推送
     *
     * @param con_id
     * @return
     */
    public MsgResult pushTop(int con_id) {
        int tag = pushListDao.updateRank(con_id);
        if (tag != 0) {
            return new MsgResult(true, "一键推送成功");
        } else
            return new MsgResult(false, "一键推送失败");
    }

    /**
     * 为指定用户手动推送
     *
     * @param con_id
     * @param uid
     * @return
     */
    public MsgResult pushTopByUser(int con_id, int uid) {
        int tag = pushListDao.updateRankByUser(con_id, uid);
        if (tag != 0) {
            return new MsgResult(true, "手动推送成功");
        } else
            return new MsgResult(false, "手动推送失败");
    }

}
